package software.hust.com.hust_last.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import software.hust.com.hust_last.presenter.LoginPresenter;
import software.hust.com.hust_last.MyApplication;
import software.hust.com.hust_last.R;
import software.hust.com.hust_last.util.ToastUtil;

public class LoginActivity extends Activity implements View.OnClickListener {
    private EditText phoneEt, pwdEt;
    private TextView loginTv;

    private LoginPresenter loginPresenter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        findView();
        loginPresenter = new LoginPresenter(this);
    }

    protected void findView() {
        phoneEt = (EditText) findViewById(R.id.login_activity_phone_et);
        pwdEt = (EditText) findViewById(R.id.login_activity_pwd_et);
        loginTv = (TextView) findViewById(R.id.activity_login_login_tv);

        loginTv.setOnClickListener(this);
    }


    /**
     * @param phone
     * @param pwd
     * @des 使用trip账号登录
     */
    public void loginTrip(String phone, String pwd) {
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.show(getApplicationContext(), "请输入手机号");
        } else if (TextUtils.isEmpty(pwd)) {
            ToastUtil.show(getApplicationContext(), "请输入密码");
        } else {
            loginPresenter.loginTrip(phone, pwd, MyApplication.mApplication.deviceToken);
        }
    }

    /**
     * @des 登录成功，跳转到主页面
     */
    public void loginSuccess() {
        Intent intent = new Intent();
        intent.setClass(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    public static boolean isPwdNo(String pwdNums) {
        Pattern p = Pattern
                .compile("([~!@#$%^&\\*()_+\\-=;':\",\\./<>?|\\s]|drop|delete|truncate|and|or)");
        Matcher m = p.matcher(pwdNums);
        if (m.find()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_login_login_tv:
                if (isPwdNo(pwdEt.getText().toString())) {
                    ToastUtil.show(getApplicationContext(), "密码错误，含有非法字符");
                } else {
                    loginTrip(phoneEt.getText().toString(), pwdEt.getText()
                            .toString());
                }
                break;
        }
    }
}
